//
//  CustomUIView.m
//  UI06_homework1
//
//  Created by aaaaaa on 16/6/13.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CustomUIView.h"
#import "CustomScrollView.h"

@interface CustomUIView ()<UIScrollViewDelegate>

@property (nonatomic, retain) CustomScrollView *scrollView;
@property (nonatomic, retain) UIPageControl *pageControl;

@end

@implementation CustomUIView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc
{
    [_imageArray release];
    [_scrollView release];
    [_pageControl release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
       
        self.imageArray = [NSArray array];
        [self createSubViews];
    }
    
    return self;
}

- (void)createSubViews{
    
    self.scrollView = [[CustomScrollView alloc] initWithFrame:self.bounds];
    [self addSubview:self.scrollView];
    self.scrollView.delegate = self;
    
    [_scrollView release];
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) / 15 * 14, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) / 15)];
    [self addSubview:self.pageControl];
    [_pageControl release];
    [self.pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged];
    
}

- (void)pageControlAction:(UIPageControl *)pageControl{
    if (pageControl.currentPage == self.imageArray.count - 1) {
        self.scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0) ;
    } else if (pageControl.currentPage == 0){
        self.scrollView.contentOffset = CGPointMake(self.bounds.size.width * (self.imageArray.count), 0) ;

    } else {
        self.scrollView.contentOffset = CGPointMake(self.bounds.size.width * (pageControl.currentPage + 1),0) ;
    }
}

- (void)setImageArray:(NSArray *)imageArray{
    if (_imageArray != imageArray) {
        [_imageArray release];
        _imageArray = [imageArray retain];
    }
    
    [self.scrollView addPicture:self.imageArray];
    self.pageControl.numberOfPages = self.imageArray.count;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.x == 0) {
        scrollView.contentOffset = CGPointMake(CGRectGetWidth(scrollView.bounds) * self.imageArray.count, 0);
        self.pageControl.currentPage = self.imageArray.count;
    } else if (scrollView.contentOffset.x == CGRectGetWidth(scrollView.bounds) * (self.imageArray.count + 1)){
        scrollView.contentOffset = CGPointMake(CGRectGetWidth(scrollView.bounds), 0);
        self.pageControl.currentPage = 0;
    } else {
        self.pageControl.currentPage = scrollView.contentOffset.x / CGRectGetWidth(scrollView.bounds) - 1;
    }
    
    
}














@end
